package com.tyj.gulimall.member.interceptor;

import com.tyj.common.constant.AuthServerConstant;
import com.tyj.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> threadLocal=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("拦截器执行成功");

        String requestURI = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match1 = matcher.match("/order/order/infoByOrderSn/**", requestURI);
        boolean match2 = matcher.match("/payed/**", requestURI);
        if (match1||match2){
            log.debug("放行 requestURI={}",requestURI);
            return true;
        }


        //判断用户是否登录(订单服务必须登录)
        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberRespVo!=null) {
            //放行
            threadLocal.set(memberRespVo);
            log.debug("放行 requestURI={}",requestURI);
            return true;
        }else {
            //返回登录页面
            session.setAttribute("msg","请先登录");
            return true;
//            response.sendRedirect("http://auth.gulimall.com/login.html");
//            log.debug("被拦截 requestURI={}",requestURI);
//            return false;

        }
    }
}
